from common.setting import ensure_path_sep
import time
import os
from .log_utils import logger
import json
from datetime import datetime
from typing import Dict, Any, List


class ReportGenerator:
    def __init__(self):
        self.report_folder = self._get_report_folder()
        self.stats: Dict[str, Any] = {
            "total_requests": 0,
            "successful_requests": 0,
            "failed_requests": 0,
            "response_times": [],
            "start_time": datetime.now().isoformat(),
            "test_duration": 0,
            "endpoints": {},
        }

    def _get_report_folder(self) -> str:
        """获取报告文件夹路径并确保其存在"""
        reports_folder = ensure_path_sep("\\reports")
        if not os.path.exists(reports_folder):
            try:
                os.makedirs(reports_folder)
                logger.info(f"报告文件夹 {reports_folder} 创建成功")
            except OSError as e:
                logger.error(f"创建报告文件夹 {reports_folder} 时出错: {e}")
        return reports_folder

    def _generate_report_filename(self) -> str:
        """生成报告文件名"""
        timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
        return f"performance_report_{timestamp}.html"

    def update_stats(self, request_data: Dict[str, Any]) -> None:
        """更新测试统计数据"""
        self.stats["total_requests"] += 1
        if request_data.get("success", False):
            self.stats["successful_requests"] += 1
        else:
            self.stats["failed_requests"] += 1

        endpoint = request_data.get("endpoint", "unknown")
        if endpoint not in self.stats["endpoints"]:
            self.stats["endpoints"][endpoint] = {
                "total": 0,
                "success": 0,
                "fail": 0,
                "response_times": [],
            }

        endpoint_stats = self.stats["endpoints"][endpoint]
        endpoint_stats["total"] += 1
        if request_data.get("success", False):
            endpoint_stats["success"] += 1
        else:
            endpoint_stats["fail"] += 1

        response_time = request_data.get("response_time", 0)
        self.stats["response_times"].append(response_time)
        endpoint_stats["response_times"].append(response_time)

    def generate_html_report(self) -> str:
        """生成HTML格式的测试报告"""
        report_path = os.path.join(self.report_folder, self._generate_report_filename())

        # 计算统计数据
        success_rate = (
            (self.stats["successful_requests"] / self.stats["total_requests"] * 100)
            if self.stats["total_requests"] > 0
            else 0
        )
        avg_response_time = (
            sum(self.stats["response_times"]) / len(self.stats["response_times"])
            if self.stats["response_times"]
            else 0
        )

        # 生成HTML报告
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>性能测试报告</title>
            <meta charset="utf-8">
            <style>
                body {{ font-family: Arial, sans-serif; margin: 20px; }}
                .summary {{ background-color: #f5f5f5; padding: 20px; border-radius: 5px; }}
                .endpoint {{ margin-top: 20px; border: 1px solid #ddd; padding: 10px; }}
                .success {{ color: green; }}
                .fail {{ color: red; }}
            </style>
        </head>
        <body>
            <h1>性能测试报告</h1>
            <div class="summary">
                <h2>测试概要</h2>
                <p>开始时间: {self.stats['start_time']}</p>
                <p>总请求数: {self.stats['total_requests']}</p>
                <p>成功率: {success_rate:.2f}%</p>
                <p>平均响应时间: {avg_response_time:.2f}ms</p>
            </div>
            <div class="endpoints">
                <h2>接口详情</h2>
        """

        # 添加每个接口的详细信息
        for endpoint, data in self.stats["endpoints"].items():
            success_rate = (
                (data["success"] / data["total"] * 100) if data["total"] > 0 else 0
            )
            avg_time = (
                sum(data["response_times"]) / len(data["response_times"])
                if data["response_times"]
                else 0
            )
            html_content += f"""
                <div class="endpoint">
                    <h3>{endpoint}</h3>
                    <p>总请求数: {data['total']}</p>
                    <p>成功率: {success_rate:.2f}%</p>
                    <p>平均响应时间: {avg_time:.2f}ms</p>
                    <p class="success">成功请求数: {data['success']}</p>
                    <p class="fail">失败请求数: {data['fail']}</p>
                </div>
            """

        html_content += """
            </div>
        </body>
        </html>
        """

        try:
            with open(report_path, "w", encoding="utf-8") as f:
                f.write(html_content)
            logger.info(f"测试报告已生成: {report_path}")
            return report_path
        except Exception as e:
            logger.error(f"生成测试报告失败: {str(e)}")
            return ""


# 创建全局的报告生成器实例
report_generator = ReportGenerator()


def get_report_path() -> str:
    """获取Locust测试报告的路径"""
    report_folder = ensure_path_sep("\\reports")
    if not os.path.exists(report_folder):
        try:
            os.makedirs(report_folder)
            logger.info(f"报告文件夹 {report_folder} 创建成功")
        except OSError as e:
            logger.error(f"创建报告文件夹 {report_folder} 时出错: {e}")

    timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
    report_name = f"locust_report_{timestamp}.html"
    return os.path.join(report_folder, report_name)
